﻿using PlutoStudio.Data.Common;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace PlutoStudio.Data
{
    public class PrimaryKey
    {
        private IEnumerable<PropertyItem> keys;
        private Dictionary<PropertyItem, object> keyValues;
        private Type entityType;

        internal PrimaryKey(Type type)
        {
            keys = PropertyFactory.GetPrimaryKeys(type);
            keyValues = new Dictionary<PropertyItem, object>();
            entityType = type;
        }

        public IEnumerable<string> Keys
        {
            get
            {
                return keys.Select(k => k.PropertyName);
            }
        }

        internal IEnumerable<PropertyItem> InternalKeys
        {
            get
            {
                return keys;
            }
        }

        public void SetValue(string key, object value)
        {
            var keyEntity = keys.FirstOrDefault(k => k.PropertyName == key);
            if (keyEntity==null)
            {
                throw new KeyNotFoundException("");
            }
            keyValues[keyEntity] = value;
        }

        internal IEnumerable<DbParameter> GetPrimaryKeyParameters()
        {
            var result = keyValues.Select(par => SqlClientProviderFactory.Provider.GenerateParameter(par.Key, par.Value));
            return result;
        }
        
        internal object GetEntity()
        {
            var entity = Activator.CreateInstance(entityType);
            foreach (var item in keyValues)
            {
                item.Key.Property.SetValue(entity, item.Value, null);
            }
            return entity;
        }
        
    }

    public class PrimaryKey<T>:PrimaryKey
    {
        public PrimaryKey():base(typeof(T))
        {

        }

        public void SetValue( Expression<Func<T, object>> property,object value)
        {
            var name = property.GetMember().Member.Name;
            base.SetValue(name, value);
        }

    }
}
